from .base import Base, train_stops
from .Stop import Stop
from .RawData import RawData
from sqlalchemy.types import Integer
from sqlalchemy.schema import Column, ForeignKey, UniqueConstraint
from sqlalchemy.databases import mysql
from sqlalchemy.orm import relation

__all__ = ["Train"]

class Train(Base):

    __tablename__ = "trains"

    id = Column(Integer, primary_key=True)
    number = Column(mysql.MSString(6), nullable=False)
    name = Column(mysql.MSString(255))
    stops = relation(Stop, secondary=train_stops)

    rawData_id = Column(Integer, ForeignKey('raw_data.id'))
    rawData = relation(RawData, lazy=True)

    __table_args__ = (UniqueConstraint("number", "name"), {})

    def __init__(self, number, name=None, stops=(), rawDataId=None):
        self.number = number
        self.name = name
        self.stops = stops
        self.rawData_id = rawDataId

    def __eq__(self, other):
        if (self.number != other.number) or (self.name != other.name) or (len(self.stops) != len(other.stops)):
            return False
        for stop in self.stops:
            if (stop not in other.stops):
                return False
        return True

    def __repr__(self):
        return "<Train('%s', '%s', '%s')>" % (self.number, self.name, self.stops)

